import pymongo

class MongoDBHandler:
    def __init__(self, url):
        print(f"MongoDB 连接字符串: {url}")
        self.client = pymongo.MongoClient(url)

    def search_documents(self, db_name, collection_name, exclude_fields=None):
        db = self.client[db_name]
        collection = db[collection_name]

        if exclude_fields is None:
            exclude_fields = ['_id']

        results = []

        for doc in collection.find():
            feed_content = doc.get('feed_content', '')
            title = feed_content["title"]
            text = feed_content["text"]
            tags = feed_content["tags"]
            if isinstance(tags, list):
                tags_str = "".join(tags)
            else:
                tags_str = str(tags)
            
            content = " ".join(filter(None, [title, text, tags_str]))
            payloads = {k: v for k, v in doc.items() if k not in exclude_fields}

            results.append({
                "content": content,
                "payloads": payloads
            })
        return results

